package com.xe.controller;

import com.xe.pojo.Books;
import com.xe.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    //    controller调用service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部图书书籍 返回到书籍展示页面
    @RequestMapping("/allbook")
    public String list(Model model) {
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allbook";
    }
//    跳转到新增图书界面

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }

    //    添加图书请求
    @RequestMapping("/addBook")
    public String addBooks(Books books) {
        System.out.println("books=>" + books);
        bookService.addBook(books);
        return "redirect:/book/allbook";  //重定向到    @RequestMapping("/allbook")
    }

//    跳转到修改界面

    @RequestMapping("/toUpdate")
    public String toUpdatePaper(int id, Model model) {
        Books books = bookService.queryBookById(id);
        model.addAttribute("QBooks", books);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String UpdateBook(Books books) {
        System.out.println("uddateBooks=>" + books);
        bookService.updateBook(books);
        return "redirect:/book/allbook";
    }

    @RequestMapping("/deleteBook/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allbook";

    }

//    查询书籍
    @RequestMapping("/queryBook")
    public String query(String queryBookName ,Model model){
        Books books=bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<>();
        list.add(books);
        if (books==null){
            list=bookService.queryAllBook();
            model.addAttribute("error","未找到");
        }
        model.addAttribute("list", list);
        return "allbook";
    }


    @RequestMapping("/")
    String index() {
        return "index";
    }
}

